angular.module('ml.services', [])

.factory('Bucket', function($rootScope) {
  // Might use a resource here that returns a JSON array

  var bucket = undefined;

  return {
    get: function() {
      if(!bucket) {
        var retrievedObject = window.localStorage.getItem('bucket');
        bucket = JSON.parse(retrievedObject);
        if(!bucket) {
          bucket = {
            name: '貓貓药箱',
            pills: []
          }
        }
      }
      return bucket;
    },
    save: function(_bucket) {
      bucket = angular.copy(_bucket);
      window.localStorage.setItem('bucket', JSON.stringify(bucket));
      $rootScope.$broadcast('bucket-updated');
      return bucket;
    }
  };
})
.factory('Plan', function($rootScope) {
  // Might use a resource here that returns a JSON array

  var plan = undefined;

  return {
    get: function() {
      if(!plan) {
        var retrievedObject = window.localStorage.getItem('plan');
        plan = JSON.parse(retrievedObject);
        if(!plan) {
          plan = {
            name: '服药计划',
            pills: []
          }
        }
      }
      return plan;
    },
    save: function(_plan) {
      plan = angular.copy(_plan);
      window.localStorage.setItem('plan', JSON.stringify(plan));
      $rootScope.$broadcast('plan-updated');
      return plan;
    }
  };
})
.factory('Status', function($rootScope) {
  // Might use a resource here that returns a JSON array

  var status = undefined;

  return {
    get: function() {
      if(!status) {
        var retrievedObject = window.localStorage.getItem('status');
        status = JSON.parse(retrievedObject);        
        if(!status) {
          status = {
            date: new Date(),
            todoList: []
          }
        }
        status.date = new Date(status.date);
      }
      return status;
    },
    save: function(_status) {
      status = angular.copy(_status);
      window.localStorage.setItem('status', JSON.stringify(status));
      return status;
    }
  };
});
